<template>
  <el-input
    class="common-input-integer"
    v-model="stringValue"
    :maxlength="maxLength"
    :placeholder="placeholder"
    :clearable="clearable"
    :disabled="disabled"
    @keyup.enter.native="$emit('enter', $event)"
  >
  </el-input>
</template>

<script>
export default {
  name: "CommonInput",
  props: {
    value: {
      type: String,
      default: "",
    },
    maxLength: {
      type: Number,
      default: 5,
    },
    placeholder: {
      type: String,
    },
    clearable: {
      type: Boolean,
      default: false,
    },
    maxValue: {
      type: Number,
      default: 100,
    },
    minValue: {
      type: Number,
      default: 0,
    },
    disabled: {
      type: Boolean,
      default: false
    }
  },
  computed: {
    stringValue: {
      get: function () {
        return this.handleSpecialChar(this.value);
      },
      set: function (v) {
        let value = this.handleSpecialChar(v);
        this.$emit("input", value);
      },
    },
  },
  methods: {
    handleSpecialChar(value) {
      let str = value.toString();
      if (value) {
        const rule = new RegExp("[^0-9.]", "gi");
        str = str.replace(rule, "");
        if (+str > this.maxValue) {
          str = this.maxValue.toString();
        }
        if (+str < this.minValue) {
          str = this.minValue.toString();
        }
        return str;
      } else {
        return str;
      }
    },
  },
};
</script>

<style scoped lang="scss">
.common-input-integer {
  width: 100px;

  ::v-deep .el-input__inner {
    text-align: left;
  }
}
</style>
